#coding:utf-8
from lovewith.share.models import Category
from lovewith.share.views.modules.attach_tag import AttachTagApi
from lovewith.utils.mtcache import MtCache
from lovewith.utils.tools import my_iterator
from lovewith.promote.views.modules.cate_tag import CatePromoteTagApi


class CategoryApi:
    def __init__(self):
        pass

    @staticmethod
    def check_data(cate_id):
        cate_data = Category.objects.filter(id=int(cate_id))
        if cate_data.exists():
            return cate_data[0]
        else:
            return False


    #获取分类&&分类下的推荐标签
    @staticmethod
    def get_all(tag_count=10):
        cate_data = MtCache('category').get(count=tag_count)

        if not cate_data:
            cate_data = []
            cate_filter_data = Category.objects.filter(parent=None).order_by('-sort')
            for cate in my_iterator(cate_filter_data):
                cate_tags = CatePromoteTagApi.get(cate.id, count=tag_count)
                cate_data.append({'id': cate.id, 'name': cate.name, 'banner': cate.banner.name, 'tags': cate_tags})

            MtCache('category').set(cate_data, count=tag_count)

        return cate_data

    #获取分类&分类下热门标签
    @staticmethod
    def get_hot_tag(tag_count=50):
        cate_data = MtCache('category_hot_tag').get(count=tag_count)

        if not cate_data:
            cate_data = []
            cate_filter_data = Category.objects.filter(parent=None).order_by('-sort')
            for cate in my_iterator(cate_filter_data):
                cate_tags = AttachTagApi.get_hot(tag_count, cate.id)
                cate_data.append({'id': cate.id, 'name': cate.name, 'banner': cate.banner.name, 'tags': cate_tags})

            MtCache('category').set(cate_data, count=tag_count)

        return cate_data